package com.yihusitian.zsxq.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yihusitian.zsxq.constant.BusinessConstant;
import com.yihusitian.zsxq.pojo.data.*;
import com.yihusitian.zsxq.service.*;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;

/**
 * @Description TODO
 * @Author LeeHo
 * @Date 2021/3/26 12:42
 */
@Slf4j
@Service
public class HtmlGenerateServiceImpl implements HtmlGenerateService {


    @Autowired
    private TopicService topicService;

    @Autowired
    private TalkService talkService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private UserService userService;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private AnswerService answerService;

    @Autowired
    private TaskService taskService;

    private static String TOPIC_TALK_DETAIL_HTML_TEMPLATE;

    private static String TOPIC_TALK_COMMENT_HTML_TEMPLATE;

    private static String TOPIC_TALK_QA_DETAIL_HTML_TEMPLATE;

    private static String TOPIC_TALK_QA_COMMENT_HTML_TEMPLATE;

    static {
        TOPIC_TALK_DETAIL_HTML_TEMPLATE = FileUtil.readUtf8String("htmltemplate/TOPIC_TALK_DETAIL.html");
        TOPIC_TALK_COMMENT_HTML_TEMPLATE = FileUtil.readUtf8String("htmltemplate/TOPIC_TALK_COMMENT.html");
        TOPIC_TALK_QA_DETAIL_HTML_TEMPLATE = FileUtil.readUtf8String("htmltemplate/TOPIC_QA_DETAIL.html");
        TOPIC_TALK_QA_COMMENT_HTML_TEMPLATE = FileUtil.readUtf8String("htmltemplate/TOPIC_QA_COMMENT.html");
    }

    @Override
    public void doGenerateHtml() {
        List<TopicDO> topicDOList = topicService.list(new LambdaQueryWrapper<TopicDO>());
        if (CollectionUtil.isNotEmpty(topicDOList)) {
            topicDOList.forEach(this::doGenerateTopicHtml);
        }
    }

    public void doGenerateTopicHtml(TopicDO topicDO) {
        String result = StrUtil.EMPTY;
        Long topicId = topicDO.getId();
        if ("talk".equals(topicDO.getType())) {
            String commentContent = this.buildTopicComments(topicId, TOPIC_TALK_COMMENT_HTML_TEMPLATE);
            TalkDO talkDO = talkService.getById(topicDO.getTalkId());
            if (talkDO != null) {
                result = TOPIC_TALK_DETAIL_HTML_TEMPLATE
                        .replace("REPLACE_MAIN_CONTENT", talkDO.getText())
                        .replace("REPLACE_COMMENTS", commentContent)
                ;
            }
        } else if ("q&a".equals(topicDO.getType())) {
            String commentContent = this.buildTopicComments(topicId, TOPIC_TALK_QA_COMMENT_HTML_TEMPLATE);
            QuestionDO questionDO = questionService.getOne(new LambdaQueryWrapper<QuestionDO>().eq(QuestionDO::getTopicId, topicId), false);
            AnswerDO answerDO = answerService.getOne(new LambdaQueryWrapper<AnswerDO>().eq(AnswerDO::getTopicId, topicId), false);
            if (questionDO != null) {
                UserDO userDO = userService.getById(questionDO.getOwnerId());
                result = TOPIC_TALK_QA_DETAIL_HTML_TEMPLATE
                        .replace("REPLACE_QUESTION_OWNER", userDO == null ? "未知" : userDO.getName())
                        .replace("REPLACE_QUESTION_CONENT", questionDO.getText())
                        .replace("REPLACE_ANSWER_CONTENT", answerDO == null ? StrUtil.EMPTY : answerDO.getText())
                        .replace("REPLACE_COMMENTS", commentContent)
                ;
            }
        } else if ("task".equals(topicDO.getType())) {
            String commentContent = this.buildTopicComments(topicId, TOPIC_TALK_COMMENT_HTML_TEMPLATE);
            TaskDO taskDO = taskService.getOne(new LambdaQueryWrapper<TaskDO>().eq(TaskDO::getTopicId, topicId), false);
            if (taskDO != null) {
                result = TOPIC_TALK_DETAIL_HTML_TEMPLATE
                        .replace("REPLACE_MAIN_CONTENT", taskDO.getText())
                        .replace("REPLACE_COMMENTS", commentContent)
                ;
            }
        } else {
            log.info("非法的主题类型, topicId:{}, type:{}");
            throw new RuntimeException("非法的主题类型");
        }
        if (StrUtil.isNotEmpty(result)) {
            FileUtil.writeString(result, new File(BusinessConstant.TOPIC_HTML_STORATE_PATH + "/" + topicDO.getId() + ".html"), CharsetUtil.UTF_8);
        }
    }

    private String buildTopicComments(Long topicId, String template) {
        StringBuilder result = new StringBuilder();
        List<CommentDO> commentList = commentService.list(new LambdaQueryWrapper<CommentDO>().eq(CommentDO::getTopicId, topicId));
        if (CollectionUtil.isNotEmpty(commentList)) {
            commentList.forEach(comment -> {
                UserDO userDO = userService.getById(comment.getOwnerId());
                result.append(
                        template
                                .replace("REPLACE_COMMENT_USER_IMAGE_URL", userDO.getAvatarUrl())
                                .replace("REPLACE_COMMENT_USER_NICK_NAME", userDO.getName())
                                .replace("REPLACE_COMMENT_ITEM_CONTENT", comment.getText())
                ).append("\n");
            });
        }
        return result.toString();
    }
}